<?php

/**
 * Created by LíJimpéy(：
 * User: Leon Lee
 * Created at: 2021/2/18-21:52
 */
namespace App\Http\Controllers\Wx;

use App\CodeResponse;
use App\Http\Controllers\Controller;

use App\Models\User;
use App\Notifications\VerificationCode;
use App\Services\UserServices;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Validator;
use Leonis\Notifications\EasySms\Channels\EasySmsChannel;
use Overtrue\EasySms\PhoneNumber;

class AuthController extends WxController
{
    /**
     * @param  Request  $request
     * @return JsonResponse
     * @throws \App\Exceptions\BusinessException
     */
    public function register(Request $request)
    {
//         获取参数
        $username = $request->input('username');
        $password = $request->input('password');
        $mobile = $request->input('mobile');
        $code = $request->input('code');

//        验证参数是否为空
        if (empty($username) || empty($password) || empty($mobile) || empty($code)) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }

//         验证用户是否存在
        $user = UserServices::getInstance()->getByUsername($username);
        if (!is_null($user)) {
            return $this->fail(CodeResponse::USER_REGISTERED);
        }

//         验证手机号格式
        $validator = Validator::make(['mobile' => $mobile], ['mobile' => 'regex:/^1[0-9]{10}$/']);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::AUTH_INVALID_MOBILE);
        }
        $user = UserServices::getInstance()->getByMobile($mobile);
        if (!is_null($user)) {
            return $this->fail(CodeResponse::AUTH_MOBILE_REGISTERED);
        }

//      验证验证码是否正确
        UserServices::getInstance()->checkCaptcha($mobile, $code);

//        写入用户表
        $user = new User();
        $user->username = $username;
        $user->password = Hash::make($password);
        $user->mobile = $mobile;
        $user->avatar = 'https://thirdwx.qlogo.cn/mmopen/vi_32/ibFY0KibR500P0SjMKZsIN8rTy43AZ3qqTygmR1Lia0gjoLBnibXr3DPWHlF0yJMgNwH9sDAetkSkvC3VjIeTNjHdA/132';
        $user->nickname = $username;
        $user->last_login_time = Carbon::now()->toDateString(); // 'Y-m-d H:i:s'
        $user->last_login_ip = $request->getClientIp();
        $user->save();

//        todo 新用户发券
//        todo 返回用户信息和token
        return $this->success([
            'token' => '',
            'userinfo' => [
                'nickname' => $username,
                'avatarUrl' => $user->avatar
            ]
        ]);
    }

    public function regCaptcha(Request $request)
    {
//         获取手机号
        $mobile = $request->input('mobile');

//         验证手机号是否合法
        if (empty($mobile)) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $validator = Validator::make(['mobile' => $mobile], ['mobile' => 'regex:/^1[0-9]{10}$/']);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::AUTH_INVALID_MOBILE);
        }
//         验证手机号是否被注册
        $user = UserServices::getInstance()->getByMobile($mobile);
        if (!is_null($user)) {
            return $this->fail(CodeResponse::AUTH_MOBILE_REGISTERED);
        }

//         防刷验证，一分钟内只能请求一次，当天只能请求10次
        $lock = Cache::add('register_captcha_lock_'.$mobile, 1, 60);
        if (!$lock) {
            return $this->fail(CodeResponse::AUTH_CAPTCHA_FREQUENCY);
        }

        $countPass = UserServices::getInstance()->checkMobileSendCaptchaCount($mobile);
        if (!$countPass) {
            return $this->fail(CodeResponse::AUTH_CAPTCHA_FREQUENCY, '验证码当天发送不能超过10次！');
        }

//        保存手机号和验证码的关系
        //      随机生成6位验证码
        $code = UserServices::getInstance()->setCaptcha($mobile);

//         发送短信
        UserServices::getInstance()->sendCaptchaMsg($mobile, $code);

        return $this->success();
    }
}
